package com.heima.article.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.mess.ArticleVisitStreamMess;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.pojos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private FreemarkerGenerator freemarkerGenerator;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadmore(ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 1);
        return ResponseResult.okResult(apArticles);

    }

    @Override
    public ResponseResult loadnew(ArticleHomeDto dto) {

        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 2);
        return ResponseResult.okResult(apArticles);
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult saveArticle(ArticleDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Long id = dto.getId();

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        // 文章id不存在即新增三表,id存在则修改
        if (id == null) {
            int insert = apArticleMapper.insert(apArticle);
            if (insert < 1) {
                log.warn("文章插入失败");
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "服务器错误,文章新增失败");
            }
            // 3.3 插入article_config表
            ApArticleConfig config = new ApArticleConfig();
            config.setIsDown(false);
            config.setIsDelete(false);
            config.setIsForward(true);
            config.setIsComment(true);
            config.setId(apArticle.getId());
            int insert1 = apArticleConfigMapper.insert(config);
            if (insert1 < 1) {
                log.warn("文章配置表插入失败");
                throw new RuntimeException("文章配置表插入失败");
            }
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            int insert2 = apArticleContentMapper.insert(apArticleContent);
            if (insert2 < 1) {
                log.warn("文章内容表插入失败");
                throw new RuntimeException("文章内容表插入失败");
            }
            // 文章静态生成
            generate(apArticle.getId());
            return ResponseResult.okResult(apArticle.getId());
        } else {
            int i = apArticleMapper.updateById(apArticle);
            if (i < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "服务器错误,文章修改失败");
            }
            ApArticleContent contentUpdate = new ApArticleContent();
            contentUpdate.setContent(dto.getContent());
            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId, id);
            int update = apArticleContentMapper.update(contentUpdate, wrapper);
            if (update < 1) {
                log.warn("文章内容表修改失败");
                throw new RuntimeException("文章内容表修改失败");
            }
            // 文章静态生成保存
            generate(id);
            return ResponseResult.okResult(id);

        }
    }

    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        boolean isFollow = false, isLike = false, isUnlike = false, isCollection = false;

        ApUser user = AppThreadLocalUtil.getUser();
        if (user != null) {
            //喜欢行为
            String likeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if (StringUtils.isNotBlank(likeBehaviorJson)) {
                isLike = true;
            }

            //不喜欢的行为
            String unLikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if (StringUtils.isNotBlank(unLikeBehaviorJson)) {
                isUnlike = true;
            }

            //是否收藏
            String collctionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + dto.getArticleId(), user.getId().toString());
            if (StringUtils.isNotBlank(collctionJson)) {
                isCollection = true;
            }

            //是否关注
            Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(), dto.getAuthorId().toString());
            System.out.println(score);
            if (score != null) {
                isFollow = true;
            }

        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isfollow", isFollow);
        resultMap.put("islike", isLike);
        resultMap.put("isunlike", isUnlike);
        resultMap.put("iscollection", isCollection);

        return ResponseResult.okResult(resultMap);
    }

    /**
     * 加载文章列表
     *
     * @param dto
     * @param firstPage true是首页 false非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, boolean firstPage) {
        if (firstPage) {
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(jsonStr)) {
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                return ResponseResult.okResult(hotArticleVoList);
            }
        }

        return load(dto);
    }
/*==============================================================7月31第11天结尾=========================================================================*/
    /**
     * 更新文章的分值 同时更新缓存中的热点文章数据
     *
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //更新数据库
        ApArticle apArticle = updateArticle(mess);
        if (apArticle == null){
            return;
        }
        //计算文章分值
        Integer score = compute(apArticle);
        // 替换当前文章对应频道的热点数据
        replaceToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        // 替换推荐频道热点数据
        replaceToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 替换缓存数据
     *
     * @param article 文章内容
     * @param score   分值
     * @param key     缓存键
     */
    private void replaceToRedis(ApArticle article, Integer score, String key) {
        // 根据key获取缓存数据
        String cache = cacheService.get(key);
        if (StringUtils.isEmpty(cache)) {
            return;
        }

        List<HotArticleVo> hotArticleVos = JSON.parseArray(cache, HotArticleVo.class);
        if (CollectionUtils.isEmpty(hotArticleVos)) {
            return;
        }

        boolean flag = false;

        // 如果当前内容存在于缓存，则替换缓存分值
        for (HotArticleVo hotArticleVo : hotArticleVos) {
            if (hotArticleVo == null) {
                continue;
            }

            if (hotArticleVo.getId().equals(article.getId())) {
                hotArticleVo.setScore(score);
                flag = true;
                break;
            }
        }

        //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
        if (flag) {
            if (hotArticleVos.size() >= 30) {
                // 排序
                hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                // 取最后一条
                HotArticleVo lastHot = hotArticleVos.get(hotArticleVos.size() - 1);
                // 如果最后一条分值比当前文章分值小，则替换
                if (lastHot.getScore() < score) {
                    hotArticleVos.remove(lastHot);
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(article, hot);
                    hot.setScore(score);
                    hotArticleVos.add(hot);
                }
            } else {
                HotArticleVo hot = new HotArticleVo();
                BeanUtils.copyProperties(article, hot);
                hot.setScore(score);
                hotArticleVos.add(hot);
            }
        }

        // 重新排序
        hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());

        // 缓存到redis
        cacheService.set(key, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 计算文章评分
     *
     * @param apArticle apArticle
     * @return Integer
     */
    private Integer compute(ApArticle apArticle) {
        Integer views = apArticle.getViews();
        Integer likes = apArticle.getLikes();
        Integer comment = apArticle.getComment();
        Integer collection = apArticle.getCollection();

        Integer score = 0;
        if (views != null) {
            score += views;
        }

        if (likes != null) {
            score += likes * 3;
        }

        if (comment != null) {
            score += comment * 5;
        }

        if (collection != null) {
            score += collection * 8;
        }

        return score;
    }

    /**
     * 更新文章MySQL数据
     *
     * @param mess messmess
     * @return ApArticle
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = apArticleMapper.selectById(mess.getArticleId());
        if (apArticle == null){
            log.warn("文章id" + mess.getArticleId() + "不存在");
            return null;
        }
        Integer views = apArticle.getViews();
        Integer likes = apArticle.getLikes();
        Integer comment = apArticle.getComment();
        Integer collection = apArticle.getCollection();

        apArticle.setComment(comment == null ? mess.getComment() : comment + mess.getComment());
        apArticle.setLikes(likes == null ? mess.getLike() : likes + mess.getLike());
        apArticle.setViews(views == null ? mess.getView() : views + mess.getView());
        apArticle.setCollection(collection == null ? mess.getCollect() : collection + mess.getCollect());

        apArticleMapper.updateById(apArticle);
        return apArticle;
    }
/*===============================================================7月31第11天结尾=================================================================================================*/
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @Async
    public void generate(Long articleId) {
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId, articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);

        if (apArticleContent == null) {
            log.warn("文章内容不存在");
            return;
        }

        HashMap<String, Object> map = new HashMap<>(1);
        map.put("content", JSON.parseArray(apArticleContent.getContent()));

        InputStream is = freemarkerGenerator.generate("article.ftl", map);
        //调用minIO插件  上传HTML页面
        String url = minIoTemplate.uploadFile("", articleId + ".html", is, "html");
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle == null) {
            log.warn("文章不存在");
            return;
        }
        //更新ApArticle 修改里面的static_url字段
        apArticle.setStaticUrl(url);
        int i = apArticleMapper.updateById(apArticle);

        if (i < 1) {
            throw new RuntimeException("文章更新url失败");
        }
        //// TODO: 2022/7/27 文章发布成功 将其保存到es中
        //发送消息 创建索引
        createArticleESIndex(apArticle, apArticleContent.getContent());


    }


    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    public void createArticleESIndex(ApArticle apArticle, String content) {

        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, vo);
        vo.setContent(content);

        kafkaTemplate.send("article.es.sync.topic", JSON.toJSONString(vo));

    }


}
